package cn.wokoba.service.trade.service.lock.factory;

import cn.wokoba.service.trade.model.entity.GroupBuyActivityEntity;
import cn.wokoba.service.trade.model.entity.TradeLockRuleCommandEntity;
import cn.wokoba.service.trade.model.entity.TradeLockRuleFilterBackEntity;
import cn.wokoba.service.trade.service.lock.filter.ActivityUsabilityRuleFilter;
import cn.wokoba.service.trade.service.lock.filter.UserTakeLimitRuleFilter;
import cn.wokoba.types.desgin.framework.link.ILogicLink;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

@Slf4j
@Service
public class TradeRuleFilterFactory {

    private final ILogicLink<TradeLockRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> logicLink;

    @Autowired
    public TradeRuleFilterFactory(List<ILogicLink<TradeLockRuleCommandEntity, DynamicContext, TradeLockRuleFilterBackEntity>> logicLinkList) {
        logicLinkList.sort(Comparator.comparingInt(this::getOrder));
        for (int i = 0; i < logicLinkList.size() - 1; i++) {
            logicLinkList.get(i).appendNext(logicLinkList.get(i + 1));  // 连接链路
        }
        this.logicLink = logicLinkList.get(0);
    }


    public TradeLockRuleFilterBackEntity openLogicLink(Long activityId, String userId) throws Exception {
        return logicLink.apply(TradeLockRuleCommandEntity.builder()
                        .activityId(activityId)
                        .userId(userId)
                        .build(),
                new TradeRuleFilterFactory.DynamicContext());
    }

    private int getOrder(ILogicLink<TradeLockRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> link) {
        if (link instanceof ActivityUsabilityRuleFilter) return 1;
        else if (link instanceof UserTakeLimitRuleFilter) return 2;
        return Integer.MAX_VALUE;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class DynamicContext {

        private GroupBuyActivityEntity groupBuyActivity;

    }
}
